﻿<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%
    string entityName = Convert.ToString(ViewData["EntityName"]);
    string fieldName = Convert.ToString(ViewData["fieldName"]);
    string mode = Convert.ToString(ViewData["Mode"]);//Filter,EditFilter,Edit
    string dataFunctionParameter = Convert.ToString(ViewData["p"]);
    string locationType = ViewData["LocationType"] == null ? "" : Convert.ToString(ViewData["LocationType"]);
    
    string cascadingChainValue = Convert.ToString(ViewData["CascadingChain"]);
    bool? requiredValue = Convert.ToString(ViewData["Required"]).ToNullableBool();
    string notSetName = ViewData["NotSetName"] == "NotSet" : Convert.ToString(ViewData["NotSetName"]);
    string dataFunctionName = Convert.ToString(ViewData["DataFunctionName"]);
    string onChangeFunctionName = Convert.ToString(ViewData["OnChangeFunctionName"]);

    string idPrefix = ViewData["IdPrefix"] == null ? "" : Convert.ToString(ViewData["IdPrefix"]);

    bool renderFirstItem = true;
    if (ViewData["RenderFirstItem"] != null)
    {
        renderFirstItem = Convert.ToBoolean(ViewData["RenderFirstItem"]);
    }
    
    bool isFilter = false;
    bool isEditFilter = false;
    bool isEdit = false;

    switch (mode)
    {
        case "Filter":
            isFilter = true;
            break;
        case "EditFilter":
            isEditFilter = true;
            break;
        case "Edit":
            isEdit = true;
            break;
        default:
            isEdit = true;
            break;
    }

    if (string.IsNullOrEmpty(cascadingChainValue))
    {
        System.Reflection.Assembly modelAssembly = System.Reflection.Assembly.LoadFile(Server.MapPath(@"~\bin\Smartec.Accounts.Camel.AMS.Model.dll"));
        Type classInfo = modelAssembly.GetType("Smartec.Accounts.Camel.AMS.Model.Entities." + entityName);
        System.Reflection.PropertyInfo propertyInfo = (System.Reflection.PropertyInfo)classInfo.GetProperty(fieldName);
        var propertyMetaData = Smartec.Accounts.Camel.AMS.Model.Facades.AMSManagerFacade.GetPropertyMetaData(propertyInfo);

        var additionalMetadataAttributes = propertyMetaData.GetCustomAttributes(typeof(AdditionalMetadataAttribute), true);


        foreach (AdditionalMetadataAttribute additionalMetadataAttribute in additionalMetadataAttributes)
        {
            switch (additionalMetadataAttribute.Name)
            {
                case "CascadingChain":
                    cascadingChainValue = additionalMetadataAttribute.Value.ToString();
                    break;
                case "Required":
                    requiredValue = Convert.ToBoolean(additionalMetadataAttribute.Value);
                    break;
                case "NotSetName":
                    notSetName = additionalMetadataAttribute.Value.ToString();
                    break;
                case "DataFunctionName":
                    dataFunctionName = additionalMetadataAttribute.Value.ToString();
                    break;
                case "OnChangeFunctionName":
                    onChangeFunctionName = additionalMetadataAttribute.Value.ToString();
                    break;
                case "LocationType":
                    locationType = additionalMetadataAttribute.Value.ToString();
                    break;
                default:
                    break;
            }
        }

        if (!requiredValue.HasValue)
        {
            requiredValue = propertyMetaData.GetCustomAttributes(typeof(RequiredAttribute), true).Count() > 0 ? true : false;
        }

    }
    
    
    string[] cascadingChain = cascadingChainValue.Split('$');
    bool required = false;
    if (requiredValue.HasValue)
    {
        required = requiredValue.Value;
    }

    bool callOnChangeFunction = !isFilter && !string.IsNullOrEmpty(onChangeFunctionName);
    bool isCustomData = !string.IsNullOrEmpty(dataFunctionName);
    bool fillCustomData = isCustomData && !string.IsNullOrEmpty(dataFunctionParameter);
    bool fillData = string.IsNullOrEmpty(dataFunctionName) || fillCustomData;

    string htmlAttributes = "";
    if (required && mode == "Edit")
    {
        htmlAttributes += @"data-val=true data-val-required=*";
    }
%>

<ul class="cascadingfieldul">
<%
    for (int i = 0; i < cascadingChain.Length; i++)
    {
        
        string[] items = cascadingChain[i].Split('!');
        
        string displayName = items[0];
        
        string tableName = items[1];
        string propertyName = items[2];
        bool isFirstItem = i == 0;
        bool isLastItem = i == (cascadingChain.Length - 1);

        bool renderProperty = !string.IsNullOrEmpty(displayName);
        string id = "";
        string parentPropertyName = "";
        if (!isFirstItem)
        {
            string[] parentItems = cascadingChain[i - 1].Split('!');
            parentPropertyName = parentItems[2];
            id = string.Format("{0}${1}{2}$", tableName, parentPropertyName, isLastItem && !string.IsNullOrEmpty(locationType) ? "$" + locationType : "");
        }

        List<KeyValuePair<string, string>> listItems = new List<KeyValuePair<string, string>>();
        if (fillData)
        {
            if (renderProperty && isFirstItem)
            {
                if (fillCustomData)
                {
                    listItems = Smartec.Accounts.Camel.AMS.Model.Facades.AMSManagerFacade.GetListItemsByMethodName(dataFunctionName, dataFunctionParameter);
                }
                else
                {
                    listItems = Smartec.Accounts.Camel.AMS.Model.Facades.AMSManagerFacade.GetListItems(tableName);
                }
            }
            else if (renderProperty)
            {
                if (!string.IsNullOrEmpty(Convert.ToString(ViewData[parentPropertyName])))
                {
                    listItems = Smartec.Accounts.Camel.AMS.Model.Facades.AMSManagerFacade.GetListItems(tableName, parentPropertyName, ViewData[parentPropertyName].ToString());
                }
            }


            if (!required && isLastItem && mode == "Edit")
            {
                displayName = notSetName;
            }

            if (renderFirstItem)
            {
                if (!required && isLastItem && mode == "Edit")
                {
                    listItems.Insert(0, new KeyValuePair<string, string>("", "-- " + notSetName + " --"));
                }
                else if (required && isLastItem && mode == "Edit")
                {
                    listItems.Insert(0, new KeyValuePair<string, string>("", string.Format("-- {0} --", displayName)));
                }
                else
                {
                    listItems.Insert(0, new KeyValuePair<string, string>("-1", string.Format("-- {0} --", displayName)));
                }
            }
        }

        string propertyId = idPrefix + propertyName;
        string parentPropertyId=idPrefix + parentPropertyName;
%>
<%if (renderProperty)
  { %>
<%--<td id="<%:propertyName%>DisplayWrapper">
<%: displayName%></td>--%>
<li id="<%:propertyId%>ValueWrapper" class="cascadingfieldli" >
<%--<%: Html.DropDownList(propertyId, new SelectList(listItems, "Key", "Value", ViewData[propertyId]), htmlAttributes)%>--%>
<select name="<%: propertyId%>" id="<%: propertyId%>" <%: htmlAttributes %>>
<% foreach (KeyValuePair<string, string> kvp in listItems)
   {
       string selected = Convert.ToString(ViewData[propertyId]) == kvp.Key ? "selected" : "";%>
   <option value="<%: kvp.Key %>" <%:selected %>><%: kvp.Value %></option>
<%} %>
</select>
</li>

<%if (!isFirstItem)
  {  %>
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%:propertyId %>").CascadingDropDown("#<%:parentPropertyId %>", '/Home/GetListItems/<%:id %>',
            {
                promptText: '-- <%: displayName%> --',
                onLoading: function () {
                    $(this).css("background-color", "#FFFFCC");
                },
                onLoaded: function () {
                    $(this).val(<%:ViewData[propertyId] %>);
                    $(this).animate({ backgroundColor: '#ffffff' }, 300);
                }
            });
    });
    </script>
    <%} %>

    <%if (isLastItem && isFilter)
  {  %>
<script type="text/javascript">
    $(document).ready(function () {
        $('#<%:propertyId %>').change(function () {
            if ($(this).val() != '') {
                $("#cascadingfilterSubmit").click();
//                $.post('/Sales/OrderDetails', $(this).serialize(), function (data) {
//                    $('#orderDetailsContainer').html(data).effect("highlight", {}, 3000);
//                }
//                );
            }
        });
    });
    </script>
    <%} %>

    <%if (isLastItem && callOnChangeFunction)
  {  %>
<script type="text/javascript">
    $(document).ready(function () {
        $('#<%:propertyId %>').change(function () {
//            if ($(this).val() != '') {
               <%:onChangeFunctionName %>($(this).val());
//            }
        });
    });
    </script>
    <%} %>

<%}
  else
  { %>
  <li class="cascadingfieldli">
  <div  id="<%:propertyId %>Empty">&nbsp;</div>
  <script type="text/javascript">
      $('#<%:propertyId %>Empty').width($('#<%:propertyId%>ValueWrapper').last().width());
//      $("#<%:propertyName%>").val('<%: ViewData[propertyName]%>');
   </script>
  </li>
<%} %>
<%} %>
</ul>